const { success } = require("../utils/jsonResult");
const { select, insert, update, remove } = require("../model/roleModel");
const {
  getRoleMenuListByRoleIds,
  bindMenuForRole,
} = require("./roleMenuServices");
const { getMenuListByIds } = require("./menuServices");
const {
  getUserRoleListByRoleId,
  bindUserForRole,
} = require("./userRoleServices");

class RoleServices {
  constructor() {}
  async getPermissionUserListByRoleId(roleId) {
    try {
      const userRoleReuslt = await getUserRoleListByRoleId(roleId);
      const userRoleList = userRoleReuslt.data;
      const userIds = userRoleList.map((item) => {
        return item.user_id;
      });
      return success("分配的用户列表", userIds);
    } catch (error) {
      throw error;
    }
  }
  async getPermissionMenuListByRoleId(roleId) {
    try {
      const menuIdArr = [];
      const roleMenuReuslt = await getRoleMenuListByRoleIds(roleId);
      const roleMenuList = roleMenuReuslt.data;
      roleMenuList.forEach((element) => {
        const menuId = element.menu_id;
        const index = menuIdArr.indexOf(menuId);
        if (index == -1) {
          menuIdArr.push(menuId);
        }
      });
      if (menuIdArr.length <= 0) {
        return success("授权菜单列表", []);
      }
      const menuIds = menuIdArr.join(",");
      const menuListResult = await getMenuListByIds(menuIds);
      const menuList=menuListResult.data
      return success("分配的用户列表", menuList);
    } catch (error) {
      throw error;
    }
  }
  async getRoleList() {
    try {
      const roleListResult = await select();
      const roleList = roleListResult.results && roleListResult.results;
      return success("角色列表", roleList);
    } catch (error) {
      throw error;
    }
  }
  async addRole(role) {
    try {
      await insert(role);
      return success("添加角色成功");
    } catch (error) {
      throw error;
    }
  }
  async updateRole(role) {
    try {
      await update(role);
      return success("修改角色成功");
    } catch (error) {
      throw error;
    }
  }
  async deleteRole(id) {
    try {
      await remove(id);
      return success("删除角色成功");
    } catch (error) {
      throw error;
    }
  }

  async assignPermission(roleId, menuIds) {
    const jsonObj = await bindMenuForRole(roleId, menuIds);
    return jsonObj;
  }

  async assignUserPermission(roleId, userIds) {
    const jsonObj = await bindUserForRole(roleId, userIds);
    return jsonObj;
  }
}
module.exports = new RoleServices();
